package com.motong.gongdan.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.CustomCellWriteHandler;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.entity.LampRequestNotice;
import com.motong.gongdan.service.DeviceInfoService;
import com.motong.gongdan.service.DeviceStatusService;
import com.motong.gongdan.service.LampRequestNoticeService;
import com.motong.gongdan.service.LampRequestService;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.vo.ExcelModel.LampRequestGetListExcelModel;
import com.motong.gongdan.vo.ExcelModel.LampTimingDetailExcelModel;
import com.motong.gongdan.vo.H5Vo.common.GroupCountVo;
import com.motong.gongdan.vo.H5Vo.common.ListTypeCountVo;
import com.motong.gongdan.vo.H5Vo.lamp.query.LampDashboardQuery;
import com.motong.gongdan.vo.H5Vo.lamp.query.LampListQuery;
import com.motong.gongdan.vo.H5Vo.lamp.vo.DashboardLampRequestVo;
import com.motong.gongdan.vo.H5Vo.lamp.vo.LampDashboardVo;
import com.motong.gongdan.vo.H5Vo.lamp.vo.LampListVo;
import com.motong.gongdan.vo.system.common.vo.VoiceCallsInfo;
import com.motong.gongdan.vo.system.device.query.StatusLogQuery;
import com.motong.gongdan.vo.system.lampRequest.query.LampTimingQuery;
import com.motong.gongdan.vo.system.lampRequest.vo.LampTimingDeviceStatusRateVo;
import com.motong.gongdan.vo.system.lampRequest.vo.LampTimingStatisticsVo;
import com.motong.gongdan.vo.system.lampRequest.vo.LampTimingTypeGroupVo;
import com.motong.gongdan.vo.system.lampRequest.vo.LampTimingVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "联络灯请求")
@RestController
@RequestMapping("/sys/lampRequest")
public class LampRequestController {

    @Resource
    private DeviceInfoService deviceInfoService;

    @Resource
    private DeviceController deviceController;

    @Resource
    private DeviceStatusService deviceStatusService;

    @Resource
    private LampRequestService lampRequestService;

    @Resource
    private LampRequestNoticeService lampRequestNoticeService;

    @PostMapping("/getList")
    @ApiOperation("联络灯报表")
    @UserLoginToken
    public ResponseData<List<LampListVo>> getList(@RequestBody(required = false) LampListQuery query) {
        query = Optional.ofNullable(query).orElse(new LampListQuery());
        Page<LampListVo> data = lampRequestService.getList(new Page<>(query.getPage(), query.getLimit()), query);
        return ResponseData.success(data.getRecords(), data.getTotal());
    }


    /*-------------------联络灯请求看板--------------*/
    @ApiOperation("联络灯看板")
    @PostMapping("/lampDashboard")
    @UserLoginToken
    public ResponseData<ListTypeCountVo<LampDashboardVo>> geList(@RequestBody(required = false) LampDashboardQuery query) {
        query = Optional.ofNullable(query).orElse(new LampDashboardQuery());
        query.setTypeCount(false);

        query = Optional.ofNullable(query).orElse(new LampDashboardQuery());
        // 设备数据
        Page<LampDashboardVo> lampDashboardData = deviceInfoService.getLampDashboardList(new Page<>(query.getPage(), query.getLimit()), query);
        List<Long> deviceIds = lampDashboardData.getRecords().stream().map(LampDashboardVo::getId).collect(Collectors.toList());

        // 联络灯请求数据
        if (!CollectionUtils.isEmpty(deviceIds)) {
            List<DashboardLampRequestVo> dashboardLampRequestVos = lampRequestService.listByDeviceIdsAndType(deviceIds, query.getTypeList());
            Map<Long, List<DashboardLampRequestVo>> deviceIdDataGroup = dashboardLampRequestVos.stream().collect(Collectors.groupingBy(DashboardLampRequestVo::getDeviceId));
            LampDashboardQuery finalQuery = query;
            lampDashboardData.getRecords().forEach(i -> {
                List<DashboardLampRequestVo> lampRequestVos = deviceIdDataGroup.getOrDefault(i.getId(), Collections.emptyList());
                if (lampRequestVos.size() > finalQuery.getMaxLampRequestNum()) {
                    lampRequestVos = lampRequestVos.subList(0, finalQuery.getMaxLampRequestNum());
                }
                i.setDashboardLampRequestVos(lampRequestVos);

            });
        }

        Date currentDate = new Date();
        ListTypeCountVo<LampDashboardVo> data = new ListTypeCountVo<LampDashboardVo>().setListData(lampDashboardData);
        // ai语音数据
        List<LampRequestNotice> lampRequestNotices = lampRequestNoticeService.getBaseMapper().getListByDeviceIds(null, currentDate, LoginUtil.getLoginUserId(), "1");
        List<VoiceCallsInfo> voiceCallsInfos = new ArrayList<>();
        lampRequestNotices.forEach(i -> {
            voiceCallsInfos.add(new VoiceCallsInfo().setText(i.getNoticeText()));
            i.setRoundNum(i.getRoundNum() - 1);
            if (i.getRoundNum() == 0) {
                i.setInfoStatus(1);
            } else {
                i.setNoticeTime(DateUtil.offsetMinute(currentDate, i.getIntervalTime()));
            }
        });
        data.setVoiceCallsInfos(voiceCallsInfos);
        lampRequestNoticeService.updateBatchById(lampRequestNotices);
        // 数量统计数据
        if (query.getTypeCount()) {
            List<GroupCountVo> typeCountDate = lampRequestService.getLampRequestTypeCount(query.getGroupId());
            data.setTypeCountData(typeCountDate);
        }
        return ResponseData.success(data);
    }

//    @PostMapping("/getDayLog")
//    @ApiOperation("联络灯日报")
//    @UserLoginToken
//    public ResponseData<List<LampListVo>> getDayLog(@RequestBody(required = false) LampListQuery query) {
//        query = Optional.ofNullable(query).orElse(new LampListQuery());
//        Page<LampListVo> data = lampRequestService.getList(new Page<>(query.getPage(), query.getLimit()), query);
//        return ResponseData.success(data.getRecords(), data.getTotal());
//    }


    @ApiOperation("联络灯时序")
    @PostMapping("/lampTiming")
    @UserLoginToken
    public ResponseData<LampTimingVo> lampTiming(@RequestBody(required = false) LampTimingQuery query) {
        query = Optional.ofNullable(query).orElse(new LampTimingQuery());
        LampTimingVo lampTimingVo = new LampTimingVo();
        LampTimingQuery finalQuery = query;
        //联络灯类型统计(时序图)
        List<LampListVo> lampRequestData = lampRequestService.getList(new Page<>(1, 4), new LampListQuery().setDeviceId(query.getDeviceId())
                .setStartTime(DateUtil.formatDateTime(query.getStartTime())).setEndTime(DateUtil.formatDate(query.getEndTime())).setOrderByTimeDesc(false)).getRecords();
        if (!CollectionUtils.isEmpty(lampRequestData)) {
            List<LampTimingStatisticsVo> data = lampRequestData.stream().map(i -> {
                LampTimingStatisticsVo statisticsVo = new LampTimingStatisticsVo().setName(i.getTypeName()).setEndTime(Optional.ofNullable(i.getFinishTime()).orElse(new Date()));
                statisticsVo.setStartTime(new DateTime(i.getCreateTime()).isBefore(finalQuery.getStartTime()) ? finalQuery.getStartTime() : i.getCreateTime())
                        .setName(i.getTypeName());
                statisticsVo.setDurationSecond(DateUtil.between(statisticsVo.getStartTime(), statisticsVo.getEndTime(), DateUnit.SECOND));
                return statisticsVo;
            }).collect(Collectors.toList());
            lampTimingVo.setLampTimingStatisticsList(data);
        }
        // 设备状态(时序图)
        List<LampTimingStatisticsVo> deviceDate = deviceController.statusLog(new StatusLogQuery().setDeviceId(query.getDeviceId())
                .setTimeStart(query.getStartTime()).setTimeEnd(query.getEndTime())).getData().stream().map(i -> {
            LampTimingStatisticsVo lampTimingStatisticsVo = new LampTimingStatisticsVo().setStartTime(new DateTime(i.getCreateTime()).isBefore(finalQuery.getStartTime()) ? finalQuery.getStartTime() : i.getCreateTime()).setName(i.getStatusName())
                    .setEndTime(i.getEndTime());
            lampTimingStatisticsVo.setDurationSecond(i.getDuration());
            return lampTimingStatisticsVo;
        }).collect(Collectors.toList());
        lampTimingVo.setDeviceStatusList(deviceDate);

        //联络灯类型时间归类列表
        Page<LampTimingTypeGroupVo> lampTypeGroupData = lampRequestService.durationGroupByType(new Page<>(query.getPage(), query.getLimit()), query);
        lampTimingVo.setLampTypeGroupList(lampTypeGroupData.getRecords());
        //设备状态占比
        List<LampTimingDeviceStatusRateVo> deviceStatusRateList = deviceStatusService.deviceStatusRate(query);
        deviceStatusRateList.forEach(i -> {
            switch (i.getStatusName()) {
                case "运行":
                    i.setStatusName("绿灯");
                    break;
                case "等待":
                    i.setStatusName("黄灯");
                    break;
                case "故障":
                    i.setStatusName("红灯");
                    break;
                case "关机":
                    i.setStatusName("关灯");
                    break;
            }
        });

        List<LampTimingDeviceStatusRateVo> realData = new ArrayList<>(4);
        realData.add(deviceStatusRateList.stream().filter(i -> "绿灯".equals(i.getStatusName())).findFirst().orElse(new LampTimingDeviceStatusRateVo().setStatusName("绿灯").setRate("0").setDurationHour(0L)));
        realData.add(deviceStatusRateList.stream().filter(i -> "黄灯".equals(i.getStatusName())).findFirst().orElse(new LampTimingDeviceStatusRateVo().setStatusName("黄灯").setRate("0").setDurationHour(0L)));
        realData.add(deviceStatusRateList.stream().filter(i -> "红灯".equals(i.getStatusName())).findFirst().orElse(new LampTimingDeviceStatusRateVo().setStatusName("红灯").setRate("0").setDurationHour(0L)));
        realData.add(deviceStatusRateList.stream().filter(i -> "关灯".equals(i.getStatusName())).findFirst().orElse(new LampTimingDeviceStatusRateVo().setStatusName("关灯").setRate("0").setDurationHour(0L)));
        lampTimingVo.setDeviceStatusRateList(realData);
        return ResponseData.success(lampTimingVo, lampTypeGroupData.getTotal());
    }

    @UserLoginToken
    @PostMapping("/exportGetList")
    @ApiOperation(value = "联络灯报表导出")
    public void exportGetList(@RequestBody(required = false) LampListQuery query, HttpServletResponse response) {
        List<LampListVo> data = this.getList(query).getData();
        if (!CollectionUtils.isEmpty(data)) {
            try {
                List<LampRequestGetListExcelModel> exportData = data.stream().map(i -> {
                    LampRequestGetListExcelModel lampRequestGetListExcelModel = new LampRequestGetListExcelModel();
                    BeanUtil.copyProperties(i, lampRequestGetListExcelModel);
                    try {
                        if (StringUtils.hasLength(i.getNoteImg())) {
                            String imgUrl = "http://124.221.174.22:8890".concat(i.getNoteImg().replace("/service", ""));
                            lampRequestGetListExcelModel.setNoteImgURL(new URL(imgUrl));
                        }
                        if (StringUtils.hasLength(i.getResultImg())) {
                            String imgUrl = "http://124.221.174.22:8890".concat(i.getResultImg().replace("/service", ""));
                            lampRequestGetListExcelModel.setResultImgURL(new URL(imgUrl));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("图片转换异常!");
                    }
                    return lampRequestGetListExcelModel;
                }).collect(Collectors.toList());
                String fileName = "联络灯报表" + System.currentTimeMillis() + ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellWriteHandler()).sheet("联络灯报表导出数据").head(LampRequestGetListExcelModel.class).doWrite(exportData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @UserLoginToken
    @PostMapping("/exportLampGroupType")
    @ApiOperation(value = "联络灯时序类型分组导出")
    public void exportLampGroupType(@RequestBody(required = false) LampTimingQuery query, HttpServletResponse response) {
        List<LampTimingTypeGroupVo> data = lampRequestService.durationGroupByType(new Page<>(query.getPage(), query.getLimit()), query).getRecords();
        if (!CollectionUtils.isEmpty(data)) {
            try {
                String fileName = "联络灯类型时长" + System.currentTimeMillis() + ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellWriteHandler()).sheet("联络灯类型时长导出数据").head(LampTimingTypeGroupVo.class).doWrite(data);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @UserLoginToken
    @PostMapping("/exportLampTimingDetail")
    @ApiOperation(value = "联络灯时序详情导出")
    public void exportLampTimingDetail(@RequestBody(required = false) LampListQuery query, HttpServletResponse response) {
        List<LampListVo> data = this.getList(query).getData();
        if (!CollectionUtils.isEmpty(data)) {
            try {
                List<LampTimingDetailExcelModel> exportData = data.stream().map(i -> {
                    LampTimingDetailExcelModel lampTimingDetailExcelModel = new LampTimingDetailExcelModel();
                    BeanUtil.copyProperties(i, lampTimingDetailExcelModel);
                    if (Objects.nonNull(i.getTotalInterval())) {
                        lampTimingDetailExcelModel.setTotalIntervalH(i.getTotalIntervalHour());
                    }
                    return lampTimingDetailExcelModel;
                }).collect(Collectors.toList());
                String fileName = "联络灯时序详情" + System.currentTimeMillis() + ".xlsx";
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                EasyExcel.write(response.getOutputStream()).registerWriteHandler(new CustomCellWriteHandler()).sheet("联络灯时序详情导出数据").head(LampTimingDetailExcelModel.class).doWrite(exportData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
